<?php

echo "=== 登录API调试 ===\n";

$baseUrl = 'http://127.0.0.1:8000/api';

// 模拟登录请求
function testLogin() {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'http://127.0.0.1:8000/api/auth/login');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
        'username' => 'admin',
        'password' => 'admin@Test1'
    ]));
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json',
        'Accept: application/json'
    ]);

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    echo "HTTP状态码: $httpCode\n";
    echo "响应内容:\n$response\n";

    $data = json_decode($response, true);
    if ($data) {
        echo "\n解析后的JSON:\n";
        print_r($data);

        if (isset($data['data']['token'])) {
            echo "\n✅ 找到Token: " . substr($data['data']['token'], 0, 20) . "...\n";
            return $data['data']['token'];
        } else {
            echo "\n❌ 未找到Token\n";
        }
    } else {
        echo "\n❌ JSON解析失败\n";
    }

    return null;
}

$token = testLogin();

if ($token) {
    echo "\n=== 测试认证后的API ===\n";

    // 测试获取用户信息
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'http://127.0.0.1:8000/api/auth/me');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Accept: application/json',
        'Authorization: Bearer ' . $token
    ]);

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    echo "用户信息API - HTTP状态码: $httpCode\n";
    echo "响应内容: $response\n";

    if ($httpCode === 200) {
        echo "✅ 用户信息获取成功\n";
    } else {
        echo "❌ 用户信息获取失败\n";
    }
}
